using Microsoft.AspNetCore.Mvc;
using AdminSG3L.Applicaticn.ServicesInterface;
using AdminSG3L.Domain.Entities;
using AdminSG3L.Applicaticn.Commands;
using Serilog;
using AdminSG3L.Applicaticn.Dtos;
using Microsoft.AspNetCore.Authorization;

namespace AdminSG3L.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
[Authorize]
public class MenuController(IMenuService menuService) : ControllerBase
{
    private readonly IMenuService _menuService = menuService;

    [HttpGet("{id}")]
    public async Task<ApiResponse<MenuDto?>> GetById(Guid id)
    {
        try
        {
            return await _menuService.GetDtoByIdAsync(id);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "MenuController.GetById异常，Id={MenuId}", id);
            return ApiResponse<MenuDto?>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpPost]
    public async Task<ApiResponse<MenuDto>> Create([FromBody] CreateMenuDto dto)
    {
        try
        {
            return await _menuService.CreateAsync(dto);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "MenuController.Create异常，Menu={Menu}", dto);
            return ApiResponse<MenuDto>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpPost("batch")]
    public async Task<ApiResponse<IEnumerable<MenuDto>>> BatchCreate([FromBody] IEnumerable<CreateMenuDto> dtos)
    {
        try
        {
            return await _menuService.BatchCreateAsync(dtos);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "MenuController.BatchCreate异常");
            return ApiResponse<IEnumerable<MenuDto>>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpPut]
    public async Task<ApiResponse<bool>> Update([FromBody] UpdateMenuDto dto)
    {
        try
        {
            return await _menuService.UpdateAsync(dto);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "MenuController.Update异常，Menu={Menu}", dto);
            return ApiResponse<bool>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpDelete("{id}")]
    public async Task<ApiResponse<bool>> Delete(Guid id)
    {
        try
        {
            return await _menuService.DeleteAsync(id);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "MenuController.Delete异常，Id={MenuId}", id);
            return ApiResponse<bool>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpPost("batch-delete")]
    public async Task<ApiResponse<int>> BatchDelete([FromBody] IEnumerable<Guid> ids)
    {
        try
        {
            return await _menuService.BatchDeleteAsync(ids);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "MenuController.BatchDelete异常");
            return ApiResponse<int>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpGet]
    public async Task<ApiResponse<IEnumerable<MenuDto>>> GetAll()
    {
        try
        {
            return await _menuService.GetAllDtoAsync();
        }
        catch (Exception ex)
        {
            Log.Error(ex, "MenuController.GetAll异常");
            return ApiResponse<IEnumerable<MenuDto>>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpGet("paged")]
    public async Task<ApiResponse<object>> GetPaged(int pageIndex, int pageSize)
    {
        try
        {
            var result = await _menuService.GetPagedDtoAsync(pageIndex, pageSize);
            if (result.IsSuccess)
            {
                var (menus, totalCount) = result.Data;
                var pagedResult = new
                {
                    Menus = menus,
                    TotalCount = totalCount,
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    TotalPages = (int)Math.Ceiling((double)totalCount / pageSize)
                };
                return ApiResponse<object>.Success(pagedResult);
            }
            return ApiResponse<object>.Fail(result.Message);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "MenuController.GetPaged异常");
            return ApiResponse<object>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpGet("count")]
    public async Task<ApiResponse<int>> GetCount()
    {
        try
        {
            return await _menuService.GetCountAsync();
        }
        catch (Exception ex)
        {
            Log.Error(ex, "MenuController.GetCount异常");
            return ApiResponse<int>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpPost("{menuId}/assign-role/{roleId}")]
    public async Task<ApiResponse<bool>> AssignRole(Guid menuId, Guid roleId)
    {
        try
        {
            return await _menuService.AssignRoleAsync(menuId, roleId);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "MenuController.AssignRole异常，MenuId={MenuId}, RoleId={RoleId}", menuId, roleId);
            return ApiResponse<bool>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpPost("{menuId}/remove-role/{roleId}")]
    public async Task<ApiResponse<bool>> RemoveRole(Guid menuId, Guid roleId)
    {
        try
        {
            return await _menuService.RemoveRoleAsync(menuId, roleId);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "MenuController.RemoveRole异常，MenuId={MenuId}, RoleId={RoleId}", menuId, roleId);
            return ApiResponse<bool>.Fail($"控制器异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取菜单树形结构 - 前端需要的接口
    /// </summary>
    [HttpGet("tree")]
    public async Task<ApiResponse<IEnumerable<MenuDto>>> GetMenuTree()
    {
        try
        {
            return await _menuService.GetAllDtoAsync();
        }
        catch (Exception ex)
        {
            Log.Error(ex, "MenuController.GetMenuTree异常");
            return ApiResponse<IEnumerable<MenuDto>>.Fail($"控制器异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取用户菜单 - 根据用户权限返回菜单
    /// </summary>
    [HttpGet("user/{userId}")]
    public async Task<ApiResponse<IEnumerable<MenuDto>>> GetUserMenus(Guid userId)
    {
        try
        {
            // 这里应该根据用户权限过滤菜单，暂时返回所有菜单
            return await _menuService.GetAllDtoAsync();
        }
        catch (Exception ex)
        {
            Log.Error(ex, "MenuController.GetUserMenus异常，UserId={UserId}", userId);
            return ApiResponse<IEnumerable<MenuDto>>.Fail($"控制器异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取角色菜单
    /// </summary>
    [HttpGet("role/{roleId}")]
    public async Task<ApiResponse<IEnumerable<MenuDto>>> GetRoleMenus(Guid roleId)
    {
        try
        {
            // 这里应该根据角色权限过滤菜单，暂时返回所有菜单
            return await _menuService.GetAllDtoAsync();
        }
        catch (Exception ex)
        {
            Log.Error(ex, "MenuController.GetRoleMenus异常，RoleId={RoleId}", roleId);
            return ApiResponse<IEnumerable<MenuDto>>.Fail($"控制器异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 设置角色菜单
    /// </summary>
    [HttpPost("role/{roleId}")]
    public Task<ApiResponse<bool>> SetRoleMenus(Guid roleId, [FromBody] IEnumerable<Guid> menuIds)
    {
        try
        {
            // 这里应该实现角色菜单设置逻辑
            return Task.FromResult(ApiResponse<bool>.Success(true, "角色菜单设置成功"));
        }
        catch (Exception ex)
        {
            Log.Error(ex, "MenuController.SetRoleMenus异常，RoleId={RoleId}", roleId);
            return Task.FromResult(ApiResponse<bool>.Fail($"控制器异常: {ex.Message}"));
        }
    }

    /// <summary>
    /// 菜单排序
    /// </summary>
    [HttpPost("sort")]
    public Task<ApiResponse<bool>> SortMenus([FromBody] object sortData)
    {
        try
        {
            // 这里应该实现菜单排序逻辑
            return Task.FromResult(ApiResponse<bool>.Success(true, "菜单排序成功"));
        }
        catch (Exception ex)
        {
            Log.Error(ex, "MenuController.SortMenus异常");
            return Task.FromResult(ApiResponse<bool>.Fail($"控制器异常: {ex.Message}"));
        }
    }
} 